﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using PSE.Framework.ProviderLoader.Configuration;
using PSE.Framework.Configuration;
using PSE.Framework.ProviderLoader;

namespace Sinacor.Infra.Service.Security.Authorization
{
    /// <summary>
    /// Classe para captura e criação da Instância do Provider de autorização do Token
    /// </summary>
    public class AuthorizationProviderFactory
    {
        private const string authorizationProviderKey = "AuthorizationProvider";
        private const string licensingProviderKey = "LicensingProvider";
        private const string CONFIG_SECTION_NAME = "serviceProviders";

        /// <summary>
        /// Retorna o provider de Autenticação
        /// </summary>
        /// <returns>Instância do provider de autenticação configurado.</returns>
        public static IAuthorizationProvider RetrieveAuthorizationProvider()
        {
            try
            {
                ProviderConfigurationSection configSection = ApplicationConfiguration.GetCurrent().GetSection<ProviderConfigurationSection>(CONFIG_SECTION_NAME);

                if (ProviderLoader<IAuthorizationProvider>.ProviderExists(configSection.Providers, authorizationProviderKey))
                {
                    return ProviderLoader<IAuthorizationProvider>.LoadProvider(configSection.Providers, authorizationProviderKey);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException("Could not create an instance of Authorization Provider configured.", ex);
            }
        }

        /// <summary>
        /// Retorna o provider de Licença
        /// </summary>
        /// <returns>Instância do provider de autenticação configurado.</returns>
        public static ILicensingProvider RetrieveLicensingProvider()
        {
            try
            {
                ProviderConfigurationSection configSection = ApplicationConfiguration.GetCurrent().GetSection<ProviderConfigurationSection>(CONFIG_SECTION_NAME);

                if (ProviderLoader<ILicensingProvider>.ProviderExists(configSection.Providers, licensingProviderKey))
                {
                    return ProviderLoader<ILicensingProvider>.LoadProvider(configSection.Providers, licensingProviderKey);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException("Could not create an instance of Licensing Provider configured.", ex);
            }
        }
    }
}
